package com.aat.dxfy.concurrent.demo2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ResThread {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(10);

		try {
			// 1
			Callable<Integer> task = new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					Count c = new Count();
					return c.getPerson(Thread.currentThread().getName());
				}
			};

			Future<Integer> res = threadPool.submit(task);

			int resC = res.get();
			System.out.println(resC);

			// 1 end

			// 2 展示了使用线程池 多线程 并行执行任务，统计结果；
			List<Callable<Integer>> tasks = new ArrayList<>();
			
			for (int i = 0; i < 100; i++) {
				Callable<Integer> t = new Callable<Integer>() {
					public Integer call() throws Exception {
						Count c = new Count();
						return c.getPerson(Thread.currentThread().getName());
					}
				};
				tasks.add(t);
			}

			List<Future<Integer>> futures = threadPool.invokeAll(tasks);
			
			int all=0;
			for (Future<Integer> future : futures) {
				all+=future.get();
			}
			System.out.println("总人口:"+all);
			// 2 end

		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		} finally {
			threadPool.shutdown();
		}
	}

}
